package com.nervenets.web;

import com.nervenets.i18n.Translator;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.entity.Result;
import com.nervenets.web.service.MailService;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.nervenets.web.controller,com.nervenets.web.rabbitmq")
public class ApplicationExceptionHandler {
    @Resource
    MailService mailService;

    /**
     * 所有异常报错
     *
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public String allExceptionHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        File errorFile = new File(JodaUtils.getTimestamp() + "-err.log");
        if (!errorFile.exists()) errorFile.createNewFile();
        PrintWriter printWriter = new PrintWriter(errorFile);
        ex.printStackTrace(printWriter);
        printWriter.flush();
        printWriter.close();

        StringBuilder params = new StringBuilder();
        params.append("传参数：<br>");
        Map map = request.getParameterMap();
        for (Object key : map.keySet()) {
            params.append(key).append(":").append(request.getParameter(String.valueOf(key))).append("<br>");
        }
        params.append(JodaUtils.timeLongToString(JodaUtils.getTimestamp() * 1000L, "MM-dd HH:mm:ss")).append("<br>");
        StackTraceElement[] stackTrace = ex.getStackTrace();
        for (StackTraceElement element : stackTrace) {
            params.append(element.toString()).append("<br>");
        }
        for (StackTraceElement element : ex.getCause().getStackTrace()) {
            params.append(element.toString()).append("<br>");
        }
        StringBuffer requestURL = request.getRequestURL();
        String errorMessage = "POST URL:" + requestURL + "<br>" + params.toString() + "<br>error:" + ex.toString();

        mailService.sendExceptions("接口", errorMessage, errorFile.getAbsolutePath());
        errorFile.delete();

        Result result = Result.failed();
        result.setData(ex.toString());
        result.setVersion("1.0");
        result.setMessage(Translator.translate("code_500"));
        return StringUtils.toJson(result);
    }
}
